package api

import (
	"blog/library"
	"blog/models"
	"fmt"
	"github.com/astaxie/beego/orm"
)

type MenuController struct {
	baseController
}

type RoleMenu struct {
	library.Menu
	Checked bool
	Child   []RoleMenu
}

var menuModel models.Menu

//var roleMenuModel backend.RoleMenu

func (m *MenuController) List() {
	menuModel.IsShow = 1
	menuAllList, total, _ := menuModel.MenuList()
	m.success(menuAllList, "", total)
}

func (m *MenuController) Edit() {
	id, _ := m.GetInt("id", -1)
	if id == -1 {
		m.error("id错误")
	}
	menu := models.NewMenu()
	if isShow, _ := m.GetInt("is_show", -1); isShow != -1 {
		menu.IsShow = isShow
	}
	menu.Id = id
	menu.IsShow, _ = m.GetInt("is_show")
	menu.Icon = m.GetString("icon")
	menu.MenuName = m.GetString("name")
	menu.MenuUrl = m.GetString("url")
	menu.Pid, _ = m.GetInt("pid")
	menu.Level, _ = m.GetInt("level")
	if _, err := models.UpdateByCondition(menu); err != nil {
		m.error(err.Error())
	}
	m.success([]int{})
}

func (m *MenuController) Delete() {
	id, err := m.GetInt64("id")
	if err != nil {
		m.error("传入错误的id")
	}
	if _, err := models.DeleteByCondition(models.MenuTable(), orm.NewCondition().And("id", id)); err != nil {
		m.error(err.Error())
	}
	m.success([]int{})
}

func (m *MenuController) Create() {
	menu := models.NewMenu()
	menu.Icon = m.GetString("icon")
	menu.MenuName = m.GetString("name")
	menu.MenuUrl = m.GetString("url")
	menu.Pid, _ = m.GetInt("pid")
	menuType, _ := m.GetInt("type")
	menu.IsShow = 1
	menu.Type = menuType
	menu.Level = menuType
	if _, err := models.Create(menu); err != nil {
		m.error(err.Error())
	}
	m.success([]int{})
}

func (m *MenuController) GetMenuList() {
	var menuId = make([]int, 0)
	menuList := library.MenuTree(m.Ctx.Request.RequestURI)
	roleId, _ := m.GetInt("role_id", 0)
	if roleId > 0 {
		roleMenu, _, _ := models.GetAllData(models.RoleMenuTable(), orm.NewCondition().And("role_id", roleId))
		fmt.Println(roleMenu)
		for _, v := range roleMenu {
			menuId = append(menuId, int(v["menu_id"].(int64)))
		}
	}
	menuRoleList := m.dealMenuList(menuList, menuId)
	m.success(menuRoleList)
}

func (m *MenuController) dealMenuList(menu []library.Menu, menuId []int) []RoleMenu {
	roleMenuList := make([]RoleMenu, 0)
	for _, v := range menu {
		var roleMenu RoleMenu
		roleMenu.Menu = v
		roleMenu.Name = "<span class=\"fa " + v.Icon + "\"></span> " + v.Name
		if library.InArray(v.Id, menuId) {
			roleMenu.Checked = true
		}
		if len(v.Child) > 0 {
			roleMenu.Child = m.dealMenuList(v.Child, menuId)
		}
		roleMenuList = append(roleMenuList, roleMenu)
	}
	return roleMenuList
}
